package com.dmall.sort.algorithm;

/**
 * 冒泡排序算法
 * @author xiao1.wang
 * @date 2021/10/7 20:19
 */
@SuppressWarnings("all")
public class BubbleSort implements Sort {
    @Override
    public void sort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        bubbleSort(arr, arr.length);
    }

    private void bubbleSort(int[] arr, int n) {
        for (int i = 0; i < n; i++) {
            boolean isSwap = false;
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                    isSwap = true;
                }
            }
            if (!isSwap) {
                break;
            }
        }
    }

    @Override
    public String getName() {
        return "冒泡排序";
    }
}
